<!--
 * @Author: 冯本桥
 * @Date: 2025-02-13 13:50:00
 * @LastEditTime: 2025-03-07 16:05:02
 * @LastEditors: 冯本桥
 * @Description:线索详情
 * @FilePath: \teach_system_fe\src\views\sellCrm\component\clueInfo.vue
-->
<template>
  <div v-loading="loading">
    <el-breadcrumb>
      <el-breadcrumb-item
        :to="{ path: '/sellCrm/clue' }"
      >线索管理</el-breadcrumb-item>
      <el-breadcrumb-item>线索详情</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="cad-box flex-card" style="margin: 20px 0">
      <div class="left-user">
        <el-avatar
          style="margin-top: 5px"
          :size="30"
          :src="img"
        >user</el-avatar>
        <div class="left-user-info">
          <div class="name-item">{{ userDate.name || "" }}</div>
          <div class="message-item">
            <span>线索级别：{{
              tableSlotValue("rankp", userDate.rankp).label
            }}</span>

            <span
              style="padding: 0 30px"
            >线索来源：{{
              tableSlotValue("list", userDate.channelId).name
            }}</span>
            <span>线索状态：{{
              tableSlotValue("zhwysStatus", userDate.zhwysStatus).label
            }}</span>
          </div>
        </div>
      </div>
      <div v-if="userDate.zhwysStatus * 1 != 3" class="right-btn">
        <el-button
          v-if="userDate.zhwysStatus * 1 >= 4"
          type="primary"
          @click="activate"
        >激活</el-button>
        <div v-else>
          <el-button type="primary" @click="add">新增跟进记录</el-button>
          <el-button class="btn-primary-box" @click="edit">编辑</el-button>
          <el-button
            class="btn-primary-box"
            @click="makeBargain"
          >成交</el-button>
          <el-button class="btn-primary-box" @click="abandon">放弃</el-button>
          <el-button class="btn-primary-box" @click="careOf">转交</el-button>
        </div>
      </div>
    </div>

    <div class="content-box">
      <div class="left-message cad-box">
        <div class="title-card">宝宝信息</div>
        <el-form
          ref="ruleForm"
          :model="userDate"
          :rules="rules"
          label-width="80px"
          label-position="left"
          class="demo-ruleForm"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="宝宝姓名" prop="childName">
                <el-input
                  v-model="userDate.childName"
                  :disabled="isFormDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="宝宝性别" prop="gender">
                <el-select
                  v-model="userDate.gender"
                  style="width: 100%"
                  clearable
                  :disabled="isFormDisabled"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) in sexList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="出生年月" prop="birthday">
                <el-date-picker
                  v-model="userDate.birthday"
                  :disabled="isFormDisabled"
                  style="width: 100%"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="宝宝月龄" prop="monthsDiff">
                <el-input
                  v-model="userDate.monthsDiff"
                  :disabled="isFormDisabled"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <div class="box-border" />
          <div class="title-card">家属信息</div>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="家长姓名" prop="name">
                <el-input v-model="userDate.name" :disabled="isFormDisabled" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关系" prop="relationship">
                <el-select
                  v-model="userDate.relationship"
                  style="width: 100%"
                  clearable
                  :disabled="isFormDisabled"
                  placeholder=""
                >
                  <el-option
                    v-for="(item, index) in relationships"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系电话" prop="mobile">
                <el-input
                  v-model="userDate.mobile"
                  :disabled="isFormDisabled"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="家庭住址" prop="homeAddress">
                <el-input
                  v-model="userDate.homeAddress"
                  :disabled="isFormDisabled"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="box-border" />
          <div class="title-card">其他</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="备注" prop="name">
                <el-input v-model="userDate.remark" :disabled="isFormDisabled" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="right-record cad-box">
        <div class="title-card">跟进记录</div>

        <el-timeline>
          <el-timeline-item
            v-for="(item, index) in recordsDate"
            :key="index"
            icon="el-icon-time"
            :timestamp="timesDate(item.actualFollowDate)"
            placement="top"
            size="large"
          >
            <el-card>
              <div style="display: flex; align-items: center">
                <el-avatar
                  :size="40"
                  :src="item.staffHeadImgUrl || img"
                >user</el-avatar>
                <span style="margin-left: 15px">{{ item.staffName }}</span>
              </div>
              <p v-if="item.channel" class="text-content">
                跟进方式：{{
                  tableStore(clueFollowTypes, item.channel).name || "-"
                }}
              </p>
              <p class="text-content">
                <span v-if="textTitleIf(item.content)">编辑内容：</span>
                {{ item.content }}
              </p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
    </div>

    <el-dialog
      title="系统提示"
      :visible.sync="dialogVisible"
      width="20%"
      :before-close="handleClose"
    >
      <div style="text-align: center">
        <el-select v-model="userId" placeholder="请选择" style="width: 100%">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.realName"
            :value="item.id"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleBtn">确 定</el-button>
      </span>
    </el-dialog>

    <el-drawer
      title="新增跟进记录"
      :visible.sync="drawer"
      :destroy-on-close="true"
      :before-close="handleCloseDrawer"
      custom-class="add-drawer"
      :wrapper-closable="false"
      size="35%"
    >
      <div style="padding: 0 20px" class="drawer-box">
        <FromPage
          ref="infoFromRef"
          :rules="addRules"
          :label-width="null"
          :from-config="configDate.infoFrom"
          @submitForm="addSubmitForm"
        />
      </div>
    </el-drawer>

    <el-drawer
      title="编辑"
      :visible.sync="editDrawer"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      :wrapper-closable="false"
      size="35%"
    >
      <div style="padding: 0 30px">
        <from-page
          ref="addFromRef"
          :label-width="null"
          :rules="configDate.rules"
          :from-config="configDate.clueAddFrom"
          @submitForm="updateEdit"
        />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import * as configDate from '../config'
import FromPage from '@/components/Basic/FromPage/index'
import img from '@/assets/phone-img.png'
import { getTransferStaffList, leadsHistory } from '../api/index'
import {
  updataSubmit,
  getClueInfo,
  updateState,
  clueTransfer,
  clueFollow
} from '../api/clue'

export default {
  components: {
    FromPage
  },
  data () {
    return {
      loading: false,
      configDate: configDate,
      userDate: {},
      idS: '',
      recordsDate: [],
      addRuleForm: {},
      userId: '',
      rules: {},
      img: img,
      addRules: configDate.addRules,
      isFormDisabled: true,
      dialogVisible: false,
      drawer: false,
      editDrawer: false,
      options: [],
      sexList: this.$store.getters.dict.sex,
      relationships: this.$store.getters.dict.relationships
    }
  },
  computed: {
    tableSlotValue () {
      return (key, value) => {
        if (value === null || value === 'null') {
          return '-'
        }
        return (
          this.configDate[key].find(
            (item) => String(item.value || item.id) === String(value)
          ) || ''
        )
      }
    },

    tableStore () {
      return (key, value) => {
        return (
          this.$store.getters.dict[key]?.find(
            (item) => item.value * 1 || item.id * 1 === value * 1
          ) || ''
        )
      }
    }
  },
  created () {
    const { id } = this.$route.query
    this.idS = id
    this.getOptions()
    this.searchInfo()
    this.getLeadsHistory()
  },
  mounted () {},
  methods: {
    textTitleIf (value) {
      if (value.includes('修改')) {
        return true
      }
      return false
    },
    timesDate (value) {
      return value ? dayjs(value).format('YYYY-MM-DD') : '-'
    },
    add () {
      this.drawer = true
      console.log('新增')
    },
    edit () {
      this.editDrawer = true
      const { homeAddress, ...rest } = JSON.parse(
        JSON.stringify(this.userDate)
      )
      console.log(homeAddress)

      const arr = {
        ...this.configDate.clueAddFrom.reduce((acc, element) => {
          acc[element.value] = rest[element.value]
          return acc
        }, {}),
        id: rest.id,
        province: rest.province,
        city: rest.city,
        area: rest.area,
        areaId: rest.areaId,
        birthday: dayjs(rest.birthday).format('YYYY-MM-DD')
      }

      this.$nextTick(() => {
        this.$refs.addFromRef.formDate = arr
      })
      console.log('编辑')
    },

    makeBargain () {
      console.log('成交')
      this.$confirm('是否确认成交?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.updataStateId('3')
        })
        .catch(() => {})
    },
    abandon () {
      this.$confirm('是否确认放弃?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.updataStateId('4')
        })
        .catch(() => {})
    },
    activate () {
      this.$confirm('是否确认激活?', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.updataStateId('1')
        })
        .catch(() => {})
    },

    careOf () {
      console.log('转交')
      this.getOptions()
      this.dialogVisible = true
    },

    handleClose () {
      this.userId = ''
      this.dialogVisible = false
    },
    dialogVisibleBtn () {
      if (this.userId === '') {
        this.$message({
          type: 'warning',
          message: '请选择转交人员!'
        })
        return
      }
      this.updataUser()
    },

    submitForm () {
      console.log('保存')
    },

    addSubmitForm (formName) {
      if (formName !== '') {
        console.log(formName, 's')
        const list = formName
        list.leadsId = this.idS
        list.areaId = this.userDate.areaId
        list.imgUrl = formName.imgUrl?.join(',') || ''
        this.addClueFollow(list)
      }
    },

    handleCloseDrawer () {
      this.drawer = false
      this.$refs.infoFromRef.resetFields()
    },

    handleAvatarSuccess (res, file) {
      this.addRuleForm.imageUrl = URL.createObjectURL(file.raw)
    },

    async getOptions () {
      const res = await getTransferStaffList({
        permission: 'teach::classes::sales_list'
      })
      this.options = res
    },
    beforeClose () {
      this.$refs.addFromRef.resetFields()
      this.$refs.addFromRef.formDate = {}
      this.editDrawer = false
    },

    // 编辑
    async updateEdit (formName) {
      if (formName !== '') {
        console.log(formName, 's')
        const arr = formName
        delete arr.homeAddress
        this.updateDate(arr)
      }
    },

    async updateDate (value) {
      try {
        // await updataSubmit({ leads: value });
        await updataSubmit(value)
        this.$message.success('编辑成功')
        this.editDrawer = false
        this.searchInfo()
      } catch (error) {
        // this.$message.error("新增失败");
      }
    },

    // 详情
    async searchInfo () {
      this.loading = true
      try {
        const res = await getClueInfo({ leadsId: this.idS })
        this.userDate = res.leads
        this.userDate.rankp = String(this.userDate.rankp)
        this.userDate.zhwysStatus = String(this.userDate.zhwysStatus)
        this.userDate.gender = String(this.userDate.gender)
      } finally {
        this.loading = false
      }
    },

    // 跟进记录
    async getLeadsHistory () {
      const res = await leadsHistory({
        leadsId: this.idS,
        pageNum: 0,
        pageSize: 999
      })
      this.recordsDate = res.content
    },

    async updataStateId (value) {
      this.loading = true
      try {
        await updateState({ leadsId: this.userDate.id, zhwysStatus: value })
        this.$message.success('成功')
        this.searchInfo()
        // eslint-disable-next-line no-empty
      } catch (error) {
      } finally {
        this.loading = false
      }
    },

    async updataUser () {
      try {
        const selectedLabel = this.options.find(
          (option) => option.id === this.userId
        ).realName
        await clueTransfer({
          leadsId: this.idS,
          staffId: this.userId,
          staffName: selectedLabel
        })
        this.$message.success('转交成功')
        this.handleClose()
        this.searchInfo()
        // eslint-disable-next-line no-empty
      } catch (error) {
        console.log(error)
      }
    },

    async addClueFollow (value) {
      try {
        await clueFollow(value)
        this.handleCloseDrawer()
        this.searchInfo()
        this.$message.success('新增成功')
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.left-user {
  display: flex;
  justify-content: space-between;
  .left-user-info {
    margin-left: 10px;
    line-height: 30px;

    .name-item {
      font-weight: bold;
    }

    .message-item {
      font-size: 13px;
      color: #808080;
    }
  }
}

.title-card {
  font-weight: bold;
  margin-bottom: 20px;
}

.flex-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-box {
  display: flex;

  .left-message {
    width: 65%;
    padding-right: 150px;

    .demo-ruleForm {
      ::v-deep .el-form-item {
        margin-bottom: 22px;
      }

      .box-border {
        margin-bottom: 30px;
        border-top: 1px solid #ebebee;
      }
    }

    ::v-deep .el-form-item {
      margin-bottom: 55px;
    }
  }
  .right-record {
    flex: 1;
    padding-left: 30px;
    margin-left: 30px;

    ::v-deep .el-card {
      background-color: #f6f8fa;
      border: 1px solid #f6f8fa;
    }
    ::v-deep .is-always-shadow {
      box-shadow: none;
    }

    ::v-deep .el-timeline-item__timestamp {
      color: black;
      font-size: 15px;
    }

    .text-content {
      margin-top: 20px;
      color: #808080;
    }
  }
}
</style>
